package com.neu.dao.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.neu.dao.IresultDao;
import com.neu.pojo.Result;

public class ResultDao implements IresultDao {
	//属性
	private File file = new File("result.json");//文件
	private ObjectMapper om = new ObjectMapper();//objmapper
	//单例模式
	private static IresultDao resultDao = new ResultDao();
	private ResultDao() {}
	public static IresultDao getInstance() {
		return resultDao;
	}
	
	@Override
	public ArrayList<Result> list(){
		ArrayList<Result> results = new ArrayList<>();//评测结果容器
		
		try {
			results = this.om.readValue(file, new TypeReference<List<Result>>() {});//反序列化
			return results;//返回
		}catch(MismatchedInputException e) {
			return results;//返回
		}catch (IOException e) {//异常
			e.printStackTrace();
			return null;//返回
		}
	}
	
	@Override
	public boolean add(Result r) {
		ArrayList<Result> results = new ArrayList<>();//评测结果容器
		
		try {
			results = this.om.readValue(file, new TypeReference<List<Result>>() {});
			results.add(r);
			om.writeValue(file, results);
			return true;//返回
		}catch(MismatchedInputException e) {
			results.add(r);
			try {
				om.writeValue(file, results);
			} catch (IOException e1) {//异常
				e1.printStackTrace();
				return false;//返回
			}
			return true;//返回
		}catch (IOException e) {//异常
			e.printStackTrace();
			return false;//返回
		}		
	}
	
}
